<template>
  <div class="purchaser-profile">
    <el-card>
      <h2>个人信息</h2>
      <el-form :model="userInfo" label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" :disabled="!isEditing"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-tag :type="getRoleType(userInfo.role)">{{ getRoleText(userInfo.role) }}</el-tag>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="userInfo.phone" :disabled="!isEditing"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="userInfo.email" :disabled="!isEditing"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input type="textarea" v-model="roleDescription" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色权限">
          <el-tag
            v-for="permission in getRolePermissions(userInfo.role)"
            :key="permission.name"
            type="info"
            effect="plain"
          >
            {{ permission.name }}
          </el-tag>
        </el-form-item>
      </el-form>
      <el-button 
        :type="isEditing ? 'primary' : 'default'" 
        @click="isEditing ? saveUserInfo() : startEditing()"
      >
        {{ isEditing ? '保存' : '修改' }}
      </el-button>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import axios from 'axios'

const userStore = useUserStore()
const userInfo = ref({
  username: '',
  role: '',
  phone: '',
  email: ''
})
const roleDescription = ref('')
const isEditing = ref(false)

// 更新用户信息的函数
const updateProfile = async (userData) => {
  try {
    // 这里应该调用实际的 API
    // const response = await axios.put('/api/users/profile', userData)
    // return response
    
    // 模拟 API 调用
    return {
      data: {
        ...userData,
        updatedAt: new Date().toISOString()
      }
    }
  } catch (error) {
    throw new Error(error.response?.data?.message || '更新用户信息失败')
  }
}

onMounted(async () => {
  try {
    // 从 userStore 中获取最新用户信息
    if (userStore.user) {
      userInfo.value = {
        ...userStore.user,
        phone: userStore.user.phone || '13800138000',
        email: userStore.user.email || 'purchaser@example.com'
      }
    } else {
      // 如果 store 中没有用户信息，尝试从本地存储获取
      const savedUserInfo = localStorage.getItem('userInfo')
      if (savedUserInfo) {
        userInfo.value = JSON.parse(savedUserInfo)
      } else {
        // 模拟获取用户信息
        userInfo.value = {
          username: '采购员',
          role: 'purchaser',
          phone: '13800138000',
          email: 'purchaser@example.com'
        }
      }
    }
    roleDescription.value = getRoleDescription(userInfo.value.role)
  } catch (error) {
    ElMessage.error(error.message || '获取用户信息失败')
  }
})

const startEditing = () => {
  isEditing.value = true
}

const saveUserInfo = async () => {
  try {
    // 调用 API 保存用户信息
    const response = await updateProfile(userInfo.value);
    // 更新 userStore 中的用户信息
    userStore.setUser(response.data);
    // 将用户信息保存到本地存储
    localStorage.setItem('userInfo', JSON.stringify(response.data));
    ElMessage.success('个人信息保存成功');
    isEditing.value = false;
  } catch (error) {
    ElMessage.error(error.message || '保存用户信息失败');
  }
}

const getRoleType = (role) => {
  const types = {
    admin: 'danger',
    purchaser: 'warning',
    salesman: 'success',
    deliveryman: 'info',
    customer: ''
  }
  return types[role] || ''
}

const getRoleText = (role) => {
  const texts = {
    admin: '系统管理员',
    purchaser: '采购员',
    salesman: '销售员',
    deliveryman: '配送员',
    customer: '客户'
  }
  return texts[role] || role
}

const getRoleDescription = (role) => {
  const descriptions = {
    admin: '系统管理员，负责整个系统的管理和维护。',
    purchaser: '采购员，负责商品采购和库存管理。',
    salesman: '销售员，负责订单处理和客户服务。',
    deliveryman: '配送员，负责商品配送和物流管理。',
    customer: '客户，可以浏览商品和下单。'
  }
  return descriptions[role] || ''
}

const getRolePermissions = (role) => {
  const permissions = {
    purchaser: [
      { name: '产品管理', description: '查看和管理产品信息' },
      { name: '采购订单', description: '创建和管理采购订单' }
    ]
  }
  return permissions[role] || []
}
</script>

<style scoped>
.purchaser-profile {
  padding: 24px;
}
</style>